package com.haoniu.common.utils.sms;

import com.alibaba.fastjson.JSONObject;
import com.haoniu.common.config.Global;
import com.haoniu.common.utils.YamlUtil;
import com.haoniu.common.utils.http.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 描述:
 * 聚合短信
 *
 * @author fei
 * @create 2019-03-19 11:04
 */
public class JuHeSms {

    private static final Logger logger = LoggerFactory.getLogger(JuHeSms.class);

    /**
     * 请求地址
     */
    private static String REQUEST_URL;

    /**
     * 密码
     */
    private static String APPKEY;

    /**
     * 模板
     */
    private static String MSG_MOBAN_ID;

    private static String ENV = "dev";

    static {
        ENV = Global.getConfig("spring.profiles.active");
        REQUEST_URL = YamlUtil.getProperty("application-" + ENV + ".yml", "sms.juhe.requestUrl");
        APPKEY = YamlUtil.getProperty("application-" + ENV + ".yml", "sms.juhe.appkey");
        MSG_MOBAN_ID = YamlUtil.getProperty("application-" + ENV + ".yml", "sms.juhe.mobanId");
    }


    /**
     * 发送普通短信验证码
     */
    public static boolean send(String phoneNum, String code) {
        try {
            // http://47.97.226.4/sms/send?mobile=手机号码&tpl_id=短信模板ID&tpl_value=%23code%23%3D654654&key=
            String param = "mobile=" + phoneNum + "&tpl_id=" + MSG_MOBAN_ID + "&tpl_value=%23code%23%3D[authCode]&key=" + APPKEY;
            param = param.replace("[authCode]", code);
            logger.info("聚合短信原始请求报文: " + param);
            String repStr = HttpUtils.sendGet(REQUEST_URL,param);
            logger.info("聚合短信响应报文 :" + repStr);
            JSONObject repJson = JSONObject.parseObject(repStr);
            if ("0".equals(repJson.getString("error_code"))) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("短信发送失败");
            return false;
        }
    }
}
